package me.pinion.controller;

import com.jfinal.plugin.activerecord.Model;
import me.pinion.Log;
import me.pinion.check.annotation.AllowRole;
import me.pinion.controller.annotation.RouteBind;
import me.pinion.model.Subscription;
import me.pinion.model.Tag;
import me.pinion.service.TagService;
import org.apache.commons.codec.Charsets;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RouteBind("/tag")
public class TagController extends Controller{

    TagService tagService;


    public void index(){

        try {
            String clazzStr = getPara("clazz");
            int targetId = getParaToInt("id");
            Class<? extends Model> clazz = (Class<? extends Model>) Class.forName(clazzStr);
            Model model = clazz.newInstance().findById(targetId);
            if (model == null){
                throw new NotFoundException();
            }
            renderJson(model);
        } catch (Exception e) {
            Log.e(e);
            renderError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    public void search() throws UnsupportedEncodingException {
        String keyword = new String(getPara("keyword").getBytes(Charsets.ISO_8859_1), Charsets.UTF_8);
        List<Tag> tags = tagService.search(keyword);
        renderJson(tags);
    }

    @AllowRole("USER")
    public void subscribe(){
        Subscription subscription = Subscription.dao.subscribe(Tag.class, getParaToInt("id"), curUser());
        renderJson(subscription);
    }

    public void top(){
        int max = getParaToInt(0);
    }


    public void top3(){
        int targetId = getParaToInt("id");
        String targetClazz = getPara("clazz");
        renderJson(Tag.dao.top(targetClazz, targetId, 3));
    }

    public void top5(){
        int targetId = getParaToInt("id");
        String targetClazz = getPara("clazz");
        renderJson(Tag.dao.top(targetClazz, targetId, 5));
    }
}
